package com.kai.mqtt.protocol;

import com.kai.mqtt.constant.AttributeKeyConstant;
import com.kai.mqtt.message.DupPubRelMessage;
import com.kai.mqtt.message.service.IDupPubRelMessageService;
import com.kai.mqtt.message.service.IDupPublishMessageService;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author weijk
 * @since 2024/6/3
 */
@Slf4j
@Component
public class PubRec extends AbstractProtocol {

    @Resource
    private IDupPubRelMessageService dupPubRelMessageService;

    @Resource
    private IDupPublishMessageService dupPublishMessageService;

    @Override
    public void process(Channel channel, MqttMessage message) {
        MqttMessageIdVariableHeader variableHeader = (MqttMessageIdVariableHeader) message.variableHeader();
        int messageId = variableHeader.messageId();
        String clientId = channel.attr(AttributeKeyConstant.CLIENT_ID).get();
        log.debug("receive - pubRec, clientId: {}, messageId: {}", clientId, messageId);

        dupPublishMessageService.remove(clientId, messageId);
        DupPubRelMessage dupPubRelMessage = new DupPubRelMessage().setMessageId(messageId);
        dupPubRelMessageService.put(clientId, dupPubRelMessage);

        MqttMessage pubRelMessage = MqttMessageFactory.newMessage(
                new MqttFixedHeader(MqttMessageType.PUBREL, false, MqttQoS.AT_MOST_ONCE, false, 0),
                MqttMessageIdVariableHeader.from(messageId), null);
        log.debug("send - pubRel, clientId: {}, messageId: {}", clientId, messageId);
        channel.writeAndFlush(pubRelMessage);
    }
}
